﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Areas.Admin.Controllers
{
    public class CategoryController : Controller
    {
        private readonly Manager.BLL.Admin.M_CategoryBll bll = new Manager.BLL.Admin.M_CategoryBll();
        private readonly Manager.BLL.Admin.M_ModuleBll moduleBll = new Manager.BLL.Admin.M_ModuleBll();
        
        /// <summary>
        /// Get方式访问列表页
        /// </summary>
        /// <returns></returns>
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "view")]
        public ActionResult Index()
        {
            var query = from c in bll.GetModelList("")
                        select new Models.Category
                        {
                            CategoryID = c.TypeID,
                            CategoryName = c.TypeName,
                            CategoryCode = c.TypeCode,
                            CategoryDesc = c.TypeDesc,
                            ModuleName = new Manager.BLL.Admin.M_ModuleBll().GetModel(c.ModuleID.Value).ModuleName,
                            ModuleID=c.ModuleID.Value
                        };
            return View(query.ToList<Models.Category>());
        }

        /// <summary>
        /// Get方式访问添加页面
        /// </summary>
        /// <returns></returns>
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "add")]
        public ActionResult Add()
        {
            
            BindSelect();
            return View();
        }

        /// <summary>
        /// 模块下拉列表框
        /// </summary>
        public void BindSelect()
        {
            IEnumerable<SelectListItem> modules = from m in moduleBll.GetModelList("ParentId=" + (int)Manager.Tools.AuthPermission.ModuleTypes.WebSet) select new SelectListItem { Value = m.ModuleId.ToString(), Text = m.ModuleName };
            ViewBag.CategorySelect = modules;
        }

        /// <summary>
        /// Post方式访问添加页面提交表单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "add")]
        public ActionResult Add(Manager.Model.Admin.M_Category model)
        {
            try
            {
                if (!moduleBll.Exists(model.ModuleID.Value))
                    ModelState.AddModelError("", Resources.Global.msg_select_exist);

                if(ModuleNameCount(model.TypeName,model.TypeID)>0)
                    ModelState.AddModelError("TypeName", Resources.Global.msg_has);

                if (ModuleCodeCount(model.TypeCode, model.TypeID) > 0)
                    ModelState.AddModelError("TypeCode", Resources.Global.msg_has);

                if (ModelState.IsValid)
                {
                    int r = bll.Add(model);
                    if (r > 0)
                        return RedirectToAction("Index", "Category");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);

        }

        /// <summary>
        /// Get方式访问编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "edit")]
        public ActionResult Edit(int id)
        {
            if (!bll.Exists(id))
                return RedirectToAction("Index");
            BindSelect();
            return View(bll.GetModel(id));
        }

        /// <summary>
        /// Post方式访问编辑页面提交表单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "edit")]
        public ActionResult Edit(int id, Manager.Model.Admin.M_Category model)
        {
            if (!moduleBll.Exists(model.ModuleID.Value))
                ModelState.AddModelError("", Resources.Global.msg_select_exist);

            if (ModuleNameCount(model.TypeName, model.TypeID) > 0)
                ModelState.AddModelError("TypeName", Resources.Global.msg_has);

            if (ModuleCodeCount(model.TypeCode, model.TypeID) > 0)
                ModelState.AddModelError("TypeCode", Resources.Global.msg_has);
            model.TypeID = id;
            try
            {
                if (ModelState.IsValid)
                {
                    
                    bool r = bll.Update(model);
                    if (r)
                        return RedirectToAction("Index", "Category");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.CategorySet, Ope = "del")]
        public ActionResult Del(int id)
        {
            //判断要删除的数据是否存在
            if(!bll.Exists(id))
                return Content("<script>alert('" + Resources.Global.msg_select_exist + "');location.href='/Admin/Category/Index';</script>");
            //判断是否存在该类别的关联项
            Manager.BLL.Admin.M_NewsBll newsBll = new Manager.BLL.Admin.M_NewsBll();
            Manager.BLL.Admin.M_ShopBll shopBll = new Manager.BLL.Admin.M_ShopBll();
            Manager.BLL.Admin.M_AboutBll aboutBll = new Manager.BLL.Admin.M_AboutBll();
            if (newsBll.GetRecordCount("NewsTypeID=" + id) > 0||
                shopBll.GetRecordCount("ShopTypeID="+id)>0||
                aboutBll.GetRecordCount("AboutTypeID="+id)>0)
            {
                return Content("<script>alert('" + Resources.Global.msg_delete_error + "');location.href='/Admin/Category/Index';</script>");
            }

            try
            {
                bool r = bll.Delete(id);
                if (r)
                    return Content("<script>alert('" + Resources.Global.msg_success + "');location.href='/Admin/Category/Index';</script>");
                else
                    return Content("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Category/Index';</script>");

            }
            catch (Exception)
            {
                return JavaScript("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/Category/Index';</script>");
            }
        }
        /// <summary>
        /// 模块编码个数
        /// </summary>
        /// <param name="ModuleCode"></param>
        /// <returns></returns>
        private int ModuleCodeCount(string CategoryCode,int ModuleID)
        {
            System.Data.DataSet ds = bll.GetList("IsValid=1 and TypeCode='" + CategoryCode + "' and TypeID!=" + ModuleID);
           if (ds != null)
           {
               if (ds.Tables[0].Rows.Count > 0)
                   return ds.Tables[0].Rows.Count;
               else
                   return 0;
           }
           else
               return 0;
        }
        /// <summary>
        /// 模块名字个数
        /// </summary>
        /// <param name="ModuleCode"></param>
        /// <returns></returns>
        private int ModuleNameCount(string CategoryName, int ModuleID)
        {
            System.Data.DataSet ds = bll.GetList("IsValid=1 and TypeName='" + CategoryName + "' and TypeID!=" + ModuleID);
            if (ds != null)
            {
                if (ds.Tables[0].Rows.Count > 0)
                    return ds.Tables[0].Rows.Count;
                else
                    return 0;
            }
            else
                return 0;
        }
    }
}
